package io.kiki.stack.netty.processor;


import io.kiki.stack.netty.channelManager.Channel;
import io.kiki.stack.netty.channelManager.ChannelContext;
import io.kiki.stack.netty.invoker.RequestContext;
import io.kiki.stack.netty.util.InetSocketAddressUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Setter
@Getter
public class BizContextImpl implements BizContext {

    private final ChannelContext channelContext;

    public BizContextImpl(ChannelContext channelContext) {
        this.channelContext = channelContext;
    }

    protected ChannelContext getRemotingContext() {
        return this.channelContext;
    }

    @Override
    public String getRemoteAddress() {
        if (null != this.channelContext) {
            ChannelHandlerContext channelHandlerContext = this.channelContext.getChannelHandlerContext();
            io.netty.channel.Channel channel = channelHandlerContext.channel();
            if (null != channel) {
                return InetSocketAddressUtil.parseRemoteAddress(channel);
            }
        }
        return "UNKNOWN_ADDRESS";
    }

    @Override
    public String getRemoteHost() {
        if (null != this.channelContext) {
            ChannelHandlerContext channelHandlerContext = this.channelContext.getChannelHandlerContext();
            io.netty.channel.Channel channel = channelHandlerContext.channel();
            if (null != channel) {
                return InetSocketAddressUtil.parseRemoteIp(channel);
            }
        }
        return "UNKNOWN_HOST";
    }

    @Override
    public int getRemotePort() {
        if (null != this.channelContext) {
            ChannelHandlerContext channelHandlerContext = this.channelContext.getChannelHandlerContext();
            io.netty.channel.Channel channel = channelHandlerContext.channel();
            if (null != channel) {
                return InetSocketAddressUtil.parseRemotePort(channel);
            }
        }
        return -1;
    }

    @Override
    public Channel getChannel() {
        if (null != this.channelContext) {
            return this.channelContext.getChannel();
        }
        return null;
    }

    @Override
    public boolean isRequestTimeout() {
        return this.channelContext.isRequestTimeout();
    }

    /**
     * get the timeout value from rpc client.
     */
    @Override
    public int getClientTimeout() {
        return this.channelContext.getTimeout();
    }

    /**
     * get the arrive time stamp
     */
    @Override
    public long getArriveTimestamp() {
        return this.channelContext.getArriveTimestamp();
    }

    @Override
    public void put(String key, String value) {
    }

    @Override
    public String get(String key) {
        return null;
    }

    @Override
    public RequestContext getInvokeContext() {
        return this.channelContext.getRequestContext();
    }
}
